# coding=utf-8
from django.shortcuts import render, HttpResponse, HttpResponseRedirect
from .models import *
from django.utils import timezone
from django.views.decorators.csrf import csrf_exempt
import json
import os
from django.shortcuts import get_object_or_404
from django.shortcuts import redirect
import random
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger


# Create your views here.

###由于js代码的高度耦合内聚，实在没法实现独立url了。总之很复杂
###所以index_front增加一个try_except接收ajax请求，后面的数据处理，就放在那个try里就没问题了
def index_front(req):
    # TODO：将get 和 post(ajax) 方法对应内容分离，增加代码可读性
    try:
        username = req.session['username']
        login_status = 1
    except:
        username = ''
        login_status = 0
    if req.method == 'POST':
        try:
            pnum = req.POST['add']  # 新增的try
            cat = req.POST["w3ls_item"]

            # username=req.POST["username"][8:]

            print(pnum, cat, username, 1)
            print("请求上是对的")
            u = User.objects.get(username=username)
            s = Sku.objects.get(name=cat)
            if Cart.objects.filter(user=u.id, sku=s.id).exists():
                item = Cart.objects.get(user=u.id, sku=s.id)
                item.quantity += 1
                item.save()
            else:
                item = Cart(quantity=pnum)
                item.user = u
                item.sku = s
                item.save()
            print(Cart.objects.all())

            # try :
            #    if(request.POST["add"]==1):
            #       print(request.POST)
            # except Exception as e :
            #     pass
            # print(req.POST)   #测试是否接收到post请求
            # print(req.POST['add'])
            '''
            数据库的代码写在这里
            '''

            return redirect(req.path)  # 保证页面不变
        except:
            print()

        try:
            # cat=req.POST["sku"]
            username = req.POST["name"][8:]

            print(req.POST)
            print('删掉')
            u = User.objects.get(username=username)

            print(req.POST)
            print('删掉')
            u = User.objects.get(username=username)

            # s=Sku.objects.get(name=cat)
            # if Cart.objects.filter(user=u.id,sku=s.id).exists():
            #     item=Cart.objects.get(user=u.id, sku=s.id)
            #     item.delete()
            # print(Cart.objects.filter(user=u.id,sku=s.id).exists())
            return redirect(req.path)  # 保证页面不变
        except:
            pass

    data = {}
    data['username'] = username
    data['login_status'] = login_status

    # pyf
    Guiter_product = Sku.objects.filter(category_name="吉他")
    data['Guiter_product'] = Guiter_product[:3]
    Violin_product = Sku.objects.filter(category_name="小提琴")
    data['Violin_product'] = Violin_product[:3]
    Piano_product = Sku.objects.filter(category_name="钢琴")
    data['Piano_product'] = Piano_product[:3]
    Saxophone_product = Sku.objects.filter(category_name="萨克斯")
    data['Saxophone_product'] = Saxophone_product[:3]
    Drum_product = Sku.objects.filter(category_name="架子鼓")
    data['Drum_product'] = Drum_product[:3]

    Products = Guiter_product | Violin_product | Piano_product | Saxophone_product | Drum_product
    data['Products'] = Products

    return render(req, 'front/index.html', data)


@csrf_exempt
def register(req):
    if (req.method == 'POST'):
        username = req.POST.get('Username')
        email = req.POST.get('Email')
        phone = req.POST.get('Phone')
        password = req.POST.get('Password')
        User.objects.create(username=username, email=email, phone=phone,
                            password=password)
        return HttpResponseRedirect('/index/')


@csrf_exempt
def check_username(req):
    username = req.POST.get('username')
    if (len(User.objects.filter(username=username)) > 0):
        result = 0
    else:
        result = 1
    return HttpResponse(json.dumps({'result': result}))


def login_front(req):
    # TODO : 利用ajax处理用户密码错误给出提示, 用户退出logout
    # req.is_ajax()
    if (req.method == 'POST'):
        username = req.POST.get('Username')
        password = req.POST.get('Password')
        try:
            user = User.objects.get(username=username, password=password)
            req.session['username'] = username
            req.session['role'] = user.role
        except:
            pass
        return HttpResponseRedirect('/index/')


def logout_front(req):
    try:
        del req.session['username']
        del req.session['role']
    except:
        pass
    return HttpResponseRedirect('/index/')


def get_left(current_page, left, num_pages):
    """
    辅助函数，获取当前页码的值得左边两个页码值，
    要注意一些细节，比如不够两个那么最左取到2，为了方便处理，包含当前页码值，
    比如当前页码值为5，那么pages = [3,4,5]
    """
    if current_page == 1:
        return []
    elif current_page == num_pages:
        l = [i - 1 for i in range(current_page, current_page - left, -1) if i - 1 > 1]
        l.sort()
        return l
    l = [i for i in range(current_page, current_page - left, -1) if i > 1]
    l.sort()
    return l


def get_right(current_page, right, num_pages):
    """
    辅助函数，获取当前页码的值得右边两个页码值，要注意一些细节，比如不够两个那么最右取到最大页码值。
    不包含当前页码值。比如当前页码值为5，那么pages = [6,7]
    """
    if current_page == num_pages:
        return []
    return [i + 1 for i in range(current_page, current_page + right - 1)
            if i < num_pages - 1]


def pagePaginator(contentlist,page):

    paginator = Paginator(contentlist, 6)  # 第二个参数为每页最多显示个数，可修改
    left = 3  # 当前页码左边显示几个页码号 -1，比如3就显示2个
    right = 3

    try:
        contentPage = paginator.page(page)
        pages = get_left(contentPage.number, left, paginator.num_pages) \
                + get_right(contentPage.number, right, paginator.num_pages)
        # 调用了两个辅助函数，根据当前页得到了左右的页码号
    except PageNotAnInteger:
        contentPage = paginator.page(1)
        pages = get_right(contentPage.number, right, paginator.num_pages)
    except EmptyPage:
        contentPage = paginator.page(paginator.num_pages)
        pages = get_left(contentPage.number, left, paginator.num_pages)

    data = {}
    data['contentPage'] = contentPage  # 当前内容页
    data['number'] = len(contentlist)
    data['pages'] = pages
    data['first_page'] = 1
    data['last_page'] = paginator.num_pages

    try:
        # 获取 pages 列表第一个值和最后一个值，主要用于在是否该插入省略号的判断，在模板文件中将会体会到它的用处。
        # 注意这里可能产生异常，因为pages可能是一个空列表，比如本身只有一个分页，那么pages就为空，因为我们永远不会获取页码为1的页码号（至少有1页，1的页码号已经固定写在模板文件中）
        data['pages_first'] = pages[0]
        data['pages_last'] = pages[-1] + 1
        # +1的原因是为了方便判断
    except IndexError:
        data['pages_first'] = 1  # 发生异常说明只有1页
        data['pages_last'] = 2
    return data


# pyf
def products_show(req):
    try:
        username = req.session['username']
        login_status = 1
    except:
        username = ''
        login_status = 0
    data = {}
    data['username'] = username
    data['login_status'] = login_status
    type = req.GET.get('type')
    brand = req.GET.get('brand')
    page = req.GET.get('page')
    if page is None:
        page = 1

    if type is not None:
        Products = Sku.objects.filter(category_name=type)
    elif brand is not None:
        Products = Sku.objects.filter(brand_name=brand)
    else:
        Products = Sku.objects.all()
    contentPage = pagePaginator(Products, page)
    data = dict(data, **contentPage)  # 合并两个dict
    data["Products"] = Products
    return render(req, 'front/products1.html', data)


def single_product(req):
    try:
        username = req.session['username']
        login_status = 1
    except:
        username = ''
        login_status = 0
    data = {}
    data['username'] = username
    data['login_status'] = login_status
    if req.method == 'GET':
        id = req.GET.get('id')
        if id is None:
            id = Sku.objects.first().id
        sku = Sku.objects.get(id=id)
        images = Sku_images.objects.filter(sku=sku)
        data['sku'] = sku
        data['images'] = images
        return render(req, 'front/single.html', data)


@csrf_exempt
def search(req):
    try:
        username = req.session['username']
        login_status = 1
    except:
        username = ''
        login_status = 0
    data = {}
    data['username'] = username
    data['login_status'] = login_status
    if req.method == 'POST':
        query = req.POST.get('query')
        page = req.GET.get('page')
        if page is None:
            page = 1
        products = Sku.objects.filter(name__contains=query)
        data["Products"] = products

        # TODO:搜索和商品展示用同一个模版，分页时会将搜索词冲掉,可以用POST方法隐藏提交brand，query，categary等。
        contentPage = pagePaginator(products, page)
        data = dict(data, **contentPage)  # 合并两个dict
        return render(req, 'front/products1.html', data)
    else:
        return HttpResponseRedirect('/index/')


@csrf_exempt
def pay(req):
    data = {}
    try:
        # user=req.POST['username'].split("：")[1]       #取用户名
        user = req.session['username']
        database_user = User.objects.get(username=user)  # 数据库对象
    except:
        return HttpResponseRedirect('/index/')

    data["username"] = user
    data["login_status"] = 1

    data["phone"] = database_user.phone
    carts = Cart.objects.filter(user=database_user.id)
    cart = []
    money = 0
    try:
        c = carts[0]  # 如果空的返回index
        for c in carts:
            # 写data
            sku = Sku.objects.get(pk=c.sku.pk)
            image = sku.picture
            money += int(sku.new_price) * int(c.quantity)
            cart.append({"sku": sku.name, "quantity": c.quantity, "image": image, "price": sku.new_price,
                         "total": int(sku.new_price) * int(c.quantity), "type": sku.type})
    except:
        return HttpResponseRedirect('/index/')
    try:
        orderId = Order.objects.last().id + 1
    except:
        orderId = 1
    try:
        add = Address.objects.get(user_id=database_user.id)
    except:
        return HttpResponseRedirect('/user_address_add/')

    data["cart_item"] = cart
    data["time"] = carts[0].create_time
    data["add"] = str(add.province) + str(add.city) + str(add.county) + str(add.address)
    data["order_id"] = "11112315468" + str(orderId)
    data["money"] = money

    return render(req, 'front/pay.html', data)


@csrf_exempt
def order_submit(req):
    # TODO：删除商品时如果多于3件，返回主页时数据库的cart删掉，但前端购物车还显示有几个
    data = {}
    try:
        username = req.session['username']
        user = User.objects.get(username=username)  # 数据库对象
    except:
        return HttpResponseRedirect('/index/')
    data["username"] = username
    name = req.POST.get('name2')
    phone = req.POST.get('phone2')
    address2 = req.POST.get('address2')
    money = req.POST.get('money2')
    note = req.POST.get('note2')

    # 写Order数据库
    add = Address.objects.get(user_id=user.id)
    order = Order(user=user, address=add)
    order.name = name
    order.phone = phone
    order.address2 = address2
    order.payment = money
    order.pay_platform = 1
    order.status = 2
    order.note = note
    order.save()

    # 写OrderInfo数据库
    carts = Cart.objects.filter(user=user.id)
    for c in carts:
        sku = Sku.objects.get(pk=c.sku.pk)
        image = sku.picture
        oi = OrderInfo(order=order, user=user, sku=sku, sku_image=image,
                       sku_name=sku.name, unit_price=sku.new_price,
                       quantity=c.quantity)
        oi.save()
    return HttpResponseRedirect('/index/')


def user_center(req):
    try:
        username = req.session['username']
    except:
        return render(req, 'front/index.html', {})
    data = {}
    data['username'] = username
    data['login_status'] = 1
    return render(req, 'front/user_center.html', data)


@csrf_exempt
def user_info(req):
    try:
        username = req.session['username']
    except:
        return render(req, 'front/index.html', {})
    data = {}
    data['username'] = username
    data['login_status'] = 1
    if req.method == 'GET':
        user = User.objects.get(username=username)
        data['user'] = user
        return render(req, 'front/user_info.html', data)
    else:
        id = req.POST.get('id')
        name = req.POST.get('name')
        admin = req.POST.get('admin')
        email = req.POST.get('e-mail')
        phone = req.POST.get('phone')
        img = req.FILES.get('Profile')

        user1 = User.objects.get(id=id)
        print(img)
        if img is not None:
            fileName = str(id) + "_" + str(random.randint(0, 99)) + '.' + img.name.split(".")[-1]
            print(fileName)
            path = 'media/img_users/'
            destination = open(path + fileName, 'wb+')
            for chunk in img.chunks():
                destination.write(chunk)
            destination.close()

        User.objects.filter(id=id).update(
            user_profile='/media/img_users/' + fileName,
            username=name,
            password=admin,
            email=email,
            phone=phone,
            grade=user1.grade,
            role=user1.role)

        return render(req, 'front/user_center.html', data)


@csrf_exempt
def user_address_add(req):
    try:
        username = req.session['username']
    except:
        return render(req, 'front/index.html', {})
    data = {}
    data['username'] = username
    data['login_status'] = 1
    if req.method == 'GET':
        user = User.objects.get(username=username)
        data['user'] = user
        return render(req, 'front/user_address_add.html', data)
    else:
        userid = req.POST.get('id')
        name = req.POST.get('name')
        prov = req.POST.get('province')
        city = req.POST.get('city')
        county = req.POST.get('county')
        add = req.POST.get('address')
        phone = req.POST.get('phone')
        postcode = req.POST.get('postcode')

        user1 = User.objects.get(id=userid)
        Address.objects.create(
            user=user1,
            name=name,
            phone=phone,
            province=prov,
            city=city,
            county=county,
            address=add,
            postcode=postcode)

        return render(req, 'front/user_center.html', data)


@csrf_exempt
def user_address(req):
    try:
        username = req.session['username']
    except:
        return render(req, 'front/index.html', {})
    data = {}
    data['username'] = username
    data['login_status'] = 1
    if req.method == 'GET':
        user = User.objects.get(username=username)
        data['user'] = user
        data['Address'] = Address.objects.get(user=user)
        return render(req, 'front/user_address.html', data)
    else:
        userid = req.POST.get('id')
        name = req.POST.get('name')
        prov = req.POST.get('province')
        city = req.POST.get('city')
        county = req.POST.get('county')
        add = req.POST.get('address')
        phone = req.POST.get('phone')
        postcode = req.POST.get('postcode')

        user1 = User.objects.get(id=userid)
        print(user1.username)
        Address.objects.filter(user=user1).update(
            name=name,
            phone=phone,
            province=prov,
            city=city,
            county=county,
            address=add,
            postcode=postcode)

        return render(req, 'front/user_center.html', data)



def user_payinfo (req):

    try:
        username = req.session['username']
    except:
        return render(req, 'front/index.html', {})
    orders = Order.objects.filter(user__username=username)
    data = {}
    data['username'] = username
    data['login_status'] = 1
    ord = []
    for o in orders:
        if o.status == 0:
            status = "已取消"
        elif o.status == 1:
            status = "未付款"
        elif o.status == 2:
            status = "已付款"
        elif o.status == 3:
            status = "已发货"
        elif o.status == 4:
            status = "交易成功"
        else:
            status = "交易失败"
        u = User.objects.get(id=o.user_id)
        add = Address.objects.get(id=o.address.pk)
        ord.append({"order_id": "11112315468" + str(o.id), "status": status, "user": u.username, "phone": u.phone,
                    "add": add.address, "money": o.payment})
        data["order"] = ord
    return render(req, 'front/user_payinfo.html', data)


# 后台
def index_back(req):
    try:
        username = req.session['username']
        role = req.session['role']
        if role == 0:
            raise Exception('没有权限')
    except:
        return render(req, 'back/login.html', {})
    data = {}
    data['username'] = username
    return render(req, 'back/index.html', data)


def login_back(req):
    if req.method == 'GET':
        del req.session['username']
        del req.session['role']
        return render(req, 'back/login.html', {})
    else:
        username = req.POST.get('username')
        password = req.POST.get('password')
        # TODO: 身份验证和错误提示
        if username == 'admin' and password == 'admin':
            req.session['username'] = username
            req.session['role'] = 0
            return HttpResponseRedirect('/index_back/')
        else:
            return render(req, 'back/login.html', {})


def products_list(req):
    try:
        username = req.session['username']
    except:
        return render(req, 'back/login.html', {})
    data = {}
    data['username'] = username
    products = Sku.objects.all()
    data['products'] = products
    return render(req, 'back/product_list.html', data)


@csrf_exempt
def products_add(req):
    try:
        username = req.session['username']
    except:
        return render(req, 'back/login.html', {})
    data = {}
    data['username'] = username
    if req.method == 'GET':
        return render(req, 'back/product_add.html', data)
    else:
        name = req.POST.get('name')
        brand_name = req.POST.get('brand')
        brand = Brand.objects.get(name=brand_name)
        category_name = req.POST.get('category')
        category = Category.objects.get(name=category_name)
        type = req.POST.get('type')
        color = req.POST.get('color')
        old_price = req.POST.get('old_price')
        new_price = req.POST.get('new_price')
        stock = req.POST.get('stock')
        status = req.POST.get('status')
        introduction = req.POST.get('introduction')
        s = Sku.objects.create(name=name, brand=brand, category=category,
                               brand_name=brand_name, category_name=category_name,
                               type=type, color=color, old_price=old_price, new_price=new_price,
                               stock=stock, status=status, introduction=introduction)

        filelist = req.FILES.getlist('pictures')
        if filelist != None:
            for i in range(len(filelist)):
                img = filelist[i]
                fileName = str(s.id) + '_' + str(i) + '.' + img.name.split(".")[-1]
                if (i == 0):
                    # 将上传的第一张图片作为商品的主图存储在sku中，方便查询
                    Sku.objects.filter(id=s.id).update(picture='/media/img_products/' + fileName)

                path = 'media/img_products/'
                destination = open(path + fileName, 'wb+')
                for chunk in img.chunks():
                    destination.write(chunk)
                destination.close()
                Sku_images.objects.create(sku=s, image='/media/img_products/' + fileName)
        return HttpResponseRedirect('/products_list/')


@csrf_exempt
def products_detail(req):
    try:
        username = req.session['username']
    except:
        return render(req, 'back/login.html', {})
    data = {}
    data['username'] = username
    if req.method == 'GET':
        id = req.GET.get('id')
        if id is None:
            id = Sku.objects.first().id
        product = Sku.objects.get(id=id)
        data['product'] = product
        data['brand'] = json.dumps(product.brand_name)
        data['category'] = json.dumps(product.category_name)
        pictures = Sku_images.objects.filter(sku_id=id)
        picList = []
        for p in pictures:
            picList.append(p.image.name.split('/')[-1])
        data['pictures'] = picList
        return render(req, 'back/product_detail.html', data)
    else:
        id = req.POST.get('id')
        name = req.POST.get('name')
        brand_name = req.POST.get('brand')
        brand = Brand.objects.get(name=brand_name)
        category_name = req.POST.get('category')
        category = Category.objects.get(name=category_name)
        type = req.POST.get('type')
        color = req.POST.get('color')
        old_price = req.POST.get('old_price')
        new_price = req.POST.get('new_price')
        stock = req.POST.get('stock')
        status = req.POST.get('status')
        introduction = req.POST.get('introduction')
        Sku.objects.filter(id=id).update(name=name, brand=brand, category=category,
                                         brand_name=brand_name, category_name=category_name,
                                         type=type, color=color, old_price=old_price, new_price=new_price,
                                         stock=stock, status=status, introduction=introduction)

        filelist = req.FILES.getlist('pictures')
        Sku_images.objects.filter(sku_id=id).delete()
        if filelist != None:
            for i in range(len(filelist)):
                img = filelist[i]
                fileName = str(id) + '_' + str(i) + '.' + img.name.split(".")[-1]
                if (i == 0):
                    # 将上传的第一张图片作为商品的主图存储在sku中，方便查询
                    Sku.objects.filter(id=id).update(picture='/media/img_products/' + fileName)

                path = 'media/img_products/'
                destination = open(path + fileName, 'wb+')
                for chunk in img.chunks():
                    destination.write(chunk)
                destination.close()
                Sku_images.objects.create(sku_id=id, image='/media/img_products/' + fileName)
        return HttpResponseRedirect('/products_list/')


@csrf_exempt
def products_delete(req):
    id = req.POST.get('id')
    try:
        # 数据库删除的同时删掉本地图片
        pictures = Sku_images.objects.filter(sku_id=id).values_list('image')
        for path in pictures:
            file_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))).replace('/', r"\\") + path[0]
            if os.path.exists(file_path):
                os.remove(file_path)
        Sku.objects.filter(id=id).delete()
        result = 'success'
    except:
        result = 'error'
    return HttpResponse(json.dumps(result), content_type='application/json')


def order_list(req):
    try:
        username = req.session['username']
    except:

        return render(req, 'back/login.html', {})
    orders = Order.objects.all()
    data = {}
    data['username'] = username
    ord = []
    for o in orders:
        if o.status == 0:
            status = "已取消"
        elif o.status == 1:
            status = "未付款"
        elif o.status == 2:
            status = "已付款"
        elif o.status == 3:
            status = "已发货"
        elif o.status == 4:
            status = "交易成功"
        else:
            status = "交易失败"
        u = User.objects.get(id=o.user_id)
        add = Address.objects.get(id=o.address.pk)
        ord.append({"order_id": "11112315468" + str(o.id), "status": status, "user": u.username, "phone": u.phone,
                    "add": add.address, "money": o.payment})
        data["order"] = ord
    return render(req, 'back/order_list.html', data)


def order_detail(req):
    try:
        username = req.session['username']
    except:
        return render(req, 'back/login.html', {})
    data = {}
    data['username'] = username
    if (req.method == 'GET'):
        id = req.GET.get('id')
        if id is None:
            order = Order.objects.first()
        else:
            id = id.split('11112315468')[-1]
            order = Order.objects.get(id=id)
        data['order'] = order
        data['order_id'] = '11112315468' + str(order.id)
        products = OrderInfo.objects.filter(order=order)
        data['products'] = products

        f = req.GET.get('f')
        if f == '1':
            # 是前台的订单详情
            data['login_status'] = 1
            return render(req, 'front/user_payinfo_detail.html', data)
        else:
            return render(req, 'back/order_detail.html', data)


def user_list(req):
    try:
        username = req.session['username']
    except:
        return render(req, 'back/login.html', {})
    data = {}
    data['username'] = username
    users = User.objects.all()
    data['users'] = users
    return render(req, 'back/user_list.html', data)


@csrf_exempt
def user_add(req):
    try:
        username = req.session['username']
    except BaseException:
        return render(req, 'back/login.html', {})
    data = {}
    data['username'] = username
    if req.method == 'GET':
        return render(req, 'back/user_add.html', data)
    else:
        name = req.POST.get('name')
        admin = req.POST.get('admin')
        grade = req.POST.get('grade')
        email = req.POST.get('e-mail')
        phone = req.POST.get('phone')
        role = req.POST.get('role')

        u = User.objects.create(
            username=name,
            password=admin,
            email=email,
            phone=phone,
            grade=grade,
            role=role)

        img = req.FILES.get('Profile')
        if img is not None:

            fileName = str(u.id) + '.' + img.name.split(".")[-1]
            User.objects.filter(id=u.id).update(user_profile='/media/img_users/' + fileName)

            path = 'media/img_users/'
            destination = open(path + fileName, 'wb+')
            for chunk in img.chunks():
                destination.write(chunk)
            destination.close()
        return HttpResponseRedirect('/user_list/')


@csrf_exempt
def user_detail(req):
    try:
        username = req.session['username']
    except BaseException:
        return render(req, 'back/login.html', {})
    data = {}
    data['username'] = username
    if req.method == 'GET':
        id = req.GET.get('id')
        if id is None:
            id = User.objects.first().id
        user = get_object_or_404(User, id=id)

        data['user'] = user
        # data['role'] = user.role
        data['grade'] = json.dumps(user.grade)
        return render(req, 'back/user_detail.html', data)
    else:
        id = req.POST.get('id')
        name = req.POST.get('name')
        admin = req.POST.get('admin')
        grade = req.POST.get('grade')
        email = req.POST.get('e-mail')
        phone = req.POST.get('phone')
        role = req.POST.get('role')

        User.objects.filter(id=id).update(
            username=name,
            password=admin,
            email=email,
            phone=phone,
            grade=grade,
            role=role)

        img = req.FILES.get('Profile')
        if img is not None:

            fileName = str(id) + '.' + img.name.split(".")[-1]
            User.objects.filter(id=id).update(user_profile='/media/img_users/' + fileName)

            path = 'media/img_users/'
            destination = open(path + fileName, 'wb+')
            for chunk in img.chunks():
                destination.write(chunk)
            destination.close()
        return HttpResponseRedirect('/user_list/')


@csrf_exempt
def user_delete(req):
    id = req.POST.get('id')
    try:
        # 数据库删除的同时删掉本地图片
        # picture = User.objects.filter(id=id).values('user_profile')
        # file_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))).replace(
        #         '/', r"\\") + picture[0]
        # if os.path.exists(file_path):
        #     os.remove(file_path)
        User.objects.filter(id=id).delete()
        result = 'success'
    except BaseException:
        result = 'error'
    return HttpResponse(json.dumps(result), content_type='application/json')


def user_rank(req):
    try:
        username = req.session['username']
    except BaseException:
        return render(req, 'back/login.html', {})
    data = {}
    data['username'] = username
    return render(req, 'back/user_rank.html', data)


def express_list(req):
    try:
        username = req.session['username']
    except BaseException:
        return render(req, 'back/login.html', {})
    data = {}
    data['username'] = username
    return render(req, 'back/express_list.html', data)


def discharge_statistic(req):
    try:
        username = req.session['username']
    except BaseException:
        return render(req, 'back/login.html', {})
    data = {}
    data['username'] = username
    return render(req, 'back/discharge_statistic.html', data)


def sales_volume(req):
    try:
        username = req.session['username']
    except BaseException:
        return render(req, 'back/login.html', {})
    data = {}
    data['username'] = username
    return render(req, 'back/sales_volume.html', data)


@csrf_exempt
def cart_save_L(request):
    print("请求上是对的")
    # try :
    #    if(request.POST["add"]==1):
    #       print(request.POST)
    # except Exception as e :
    #     pass
    print(request.POST)
    print(request.POST['add'])
    return redirect(request.path)


@csrf_exempt
def delete_item(request):
    # 在这里，做后一步得处理，数据库删除一项就可以
    p = request.POST["cart_delete"]  # 才看被叉叉的是谁
    username = request.POST["user"][8:]
    print(p)
    print(request.path)
    print(request.POST)
    u = User.objects.get(username=username)
    s = Sku.objects.get(name=p)
    if Cart.objects.filter(user=u.id, sku=s.id).exists():
        item = Cart.objects.get(user=u.id, sku=s.id)
        item.delete()
    return redirect('/')  # 采用异步，所以无所谓，只为了返回而已，无关路径


@csrf_exempt
def change_item(request):
    # 在这里，做后一步得处理，数据库删除一项就可以
    p = request.POST["change_item"]  # 才看被改的是谁
    n = request.POST["change_num"]
    username = request.POST["user"][8:]
    print(p, n)
    print(request.path)
    print(request.POST)
    u = User.objects.get(username=username)
    s = Sku.objects.get(name=p)
    if Cart.objects.filter(user=u.id, sku=s.id).exists():
        print('change to' + n)
        item = Cart.objects.get(user=u.id, sku=s.id)
        item.quantity = n
        item.save()
    return redirect('/')  # 采用异步，所以无所谓，只为了返回而已，无关路径
